package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entify.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     */
    @PostMapping
    public R saveCategory(@RequestBody Category category, HttpSession httpSession) {

        boolean save = categoryService.save(category);

        return save ? R.success("新增分类成功") : R.error("新增分类失败");
    }

    /**
     * 分类查询
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize) {

        Page<Category> pageInfo = new Page<>(page ,pageSize);
        categoryService.page(pageInfo);
        long total = pageInfo.getTotal();
        List<Category> records = pageInfo.getRecords();
        Map map = new HashMap();
        map.put("total",total);
        map.put("records",records);
        return R.success(map);
    }

    /**
     * 删除新增
     */
    @DeleteMapping
    public R deleteById(Long id) {
        R r = categoryService.deleteById(id);
        return r;
    }
    /**
     * 修改新增分类
     */
    @PutMapping
    public R update(@RequestBody Category category, HttpSession httpSession){

        boolean updateById = categoryService.updateById(category);

        return updateById?R.success("修改分类成功"):R.error("修改分类失败");
    }

    /**
     * 查询分类
     */
    @GetMapping("/list")//修改接口以致于实现前端页面的菜品展示
    public R list(Integer type){
        //条件构造器
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        //添加条件
        qw.eq(type!=null,Category::getType,type );
        //添加排序条件
        qw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(qw);
        return R.success(list);
    }
}
